package sdk;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

public class Client {
    private String appId;
    private String appSecret;
    private String baseUrl;
    private HttpClient httpClient;

    public Client(String appId, String appSecret, String baseUrl) {
        this.appId = appId;
        this.appSecret = appSecret;
        this.baseUrl = baseUrl;
        this.httpClient = HttpClient.newHttpClient(); // 初始化 HttpClient
    }

    public static Client newClient(String appId, String appSecret, String baseUrl) {
        return new Client(appId, appSecret, baseUrl);
    }

    public Map<String, Object> post(String endpoint, Map<String, Object> postParams) {
        try {
            // 将 postParams 转换为 JSON 字符串
            String jsonBody = convertMapToJson(postParams);

            // 构建 POST 请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl + endpoint))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .build();

            // 发送请求并获取响应
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // 检查 HTTP 状态码
            if (response.statusCode() != 200) {
                throw new RuntimeException("接口返回错误: " + response.body());
            }

            // 解析响应体为 Map
            Map<String, Object> responseBody = parseJsonToMap(response.body());

            if (!responseBody.get("code").equals("1")) {
                throw new RuntimeException("接口返回错误>" + responseBody.get("message"));
            }

            return responseBody;
        } catch (Exception e) {
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }
    }

    public Map<String, Object> get(String endpoint, Map<String, Object> getParams) {
        try {
            String url = baseUrl + endpoint + "?" + buildQueryString(getParams);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .build();
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() != 200) {
                throw new RuntimeException("接口返回错误::" + response.body());
            }
            Map<String, Object> responseBody = parseJsonToMap(response.body());
            if (!responseBody.get("code").equals("1")) {
                throw new RuntimeException("接口返回错误>>" + responseBody.get("message"));
            }
            return responseBody;
        } catch (Exception e) {
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }
    }

    public String getAppId() {
        return appId;
    }

    public String getAppSecret() {
        return appSecret;
    }

    // 辅助方法：将 Map 转换为 JSON 字符串（简单实现）
    private String convertMapToJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            json.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\",");
        }
        if (json.length() > 1) {
            json.deleteCharAt(json.length() - 1); // 删除最后一个逗号
        }
        json.append("}");
        return json.toString();
    }

    // 辅助方法：将 JSON 字符串解析为 Map（简单实现）
    private Map<String, Object> parseJsonToMap(String json) {
        Map<String, Object> mapf = new HashMap<>();
        json = json.trim().replaceAll("^\\{|\\}$", ""); // 去掉大括号
        String[] pairs = json.split(",");
        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            if (keyValue.length == 2) {
                String key = keyValue[0].trim().replaceAll("\"", "");
                String value = keyValue[1].trim().replaceAll("\"", "");
                mapf.put(key, value);
            }
        }
        return mapf;
    }

    // 辅助方法：构建查询字符串
    private String buildQueryString(Map<String, Object> params) {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            queryString.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1); // 删除最后一个 &
        }
        return queryString.toString();
    }
}